import React from 'react';
import { List, Card, Button, Space, Typography, Dropdown } from 'antd';
import { EditOutlined, DeleteOutlined, EyeOutlined, MoreOutlined } from '@ant-design/icons';
import type { TableColumnConfig } from './index.tsx';

const { Text } = Typography;

export interface ListItemsProps {
  columns: TableColumnConfig[];
  dataSource: any[];
  loading?: boolean;
  onDetail: (record: any) => void;
  onEdit?: (record: any) => void;
  onDelete?: (record: any) => void;
  enableEdit?: boolean;
  enableDelete?: boolean;
  isMobile?: boolean;
  extraButtonMenu?: (record: any) => {
    key: string;
    label: string;
    icon?: React.ReactNode;
    onClick: () => void;
  }[];
  pagination?: {
    current: number;
    pageSize: number;
    total: number;
    onChange: (page: number, pageSize: number) => void;
    showSizeChanger?: boolean;
    showQuickJumper?: boolean;
    showTotal?: (total: number) => string;
  };
  onRowClick?: (record: any) => void;
}

const ListItems: React.FC<ListItemsProps> = ({
  columns,
  dataSource,
  loading,
  onDetail,
  onEdit,
  onDelete,
  enableEdit,
  enableDelete,
  isMobile,
  extraButtonMenu,
  pagination,
  onRowClick
}: ListItemsProps) => {
  const renderListItem = (item: any) => {
    const mainTitle = item[columns[0]?.dataIndex] || '';
    const price = columns.find(col => col.dataIndex === 'price' || col.title.includes('价格'));
    
    // 只有当 columns 中存在 key === "operate" 的列时才显示操作按钮
    const hasOperateColumn = columns.some(col => col.key === "operate");
    
    const actions = hasOperateColumn ? [
      <Button
        key="detail"
        icon={<EyeOutlined />}
        onClick={() => onDetail(item)}
        size="small"
      >
        {isMobile ? "" : "详情"}
      </Button>
    ] : [];

    if (hasOperateColumn && enableEdit) {
      actions.push(
        <Button
          key="edit"
          icon={<EditOutlined />}
          onClick={() => onEdit?.(item)}
          size="small"
        >
          {isMobile ? "" : "编辑"}
        </Button>
      );
    }

    if (hasOperateColumn && enableDelete) {
      actions.push(
        <Button
          key="delete"
          icon={<DeleteOutlined />}
          danger
          onClick={() => onDelete?.(item)}
          size="small"
        >
          {isMobile ? "" : "删除"}
        </Button>
      );
    }

    // 添加额外的按钮菜单
    if (hasOperateColumn && extraButtonMenu) {
      const extraButtons = extraButtonMenu(item);
      if (extraButtons && extraButtons.length > 0) {
        actions.push(
          <Dropdown
            key="more"
            menu={{
              items: extraButtons.map(btn => ({
                key: btn.key,
                label: btn.label,
                icon: btn.icon,
                onClick: btn.onClick
              }))
            }}
            trigger={['click']}
          >
            <Button
              size="small"
              icon={<MoreOutlined />}
            >
              {isMobile ? "" : "更多"}
            </Button>
          </Dropdown>
        );
      }
    }

    return (
      <List.Item>
        <Card
          hoverable
          className="w-full"
          actions={actions.length > 0 ? actions : undefined}
          onClick={(e) => {
            // 防止点击按钮时触发行点击
            if ((e.target as HTMLElement).tagName !== 'BUTTON' && onRowClick) {
              onRowClick(item);
            }
          }}
        >
          <Card.Meta
            title={mainTitle}
            description={
              <Space direction="vertical" size="small">
                {columns.slice(1).map((col, index) => {
                  if (col.dataIndex !== price?.dataIndex && 
                      col.dataIndex !== 'operate' && 
                      col.title !== '操作' &&
                      !col.key?.toString().includes('operation')) {
                    const value = col.render ? col.render(item[col.dataIndex], item) : item[col.dataIndex];
                    return (
                      <Text key={index}>
                        <Text strong>{col.title}:</Text> {value || '无'}
                      </Text>
                    );
                  }
                  return null;
                })}
                {price && (
                  <Text>
                    <Text strong>{price.title}:</Text> ¥
                    {price.render 
                      ? price.render(item[price.dataIndex], item) 
                      : parseFloat(item[price.dataIndex]).toFixed(2)}
                  </Text>
                )}
              </Space>
            }
          />
        </Card>
      </List.Item>
    );
  };

  return (
    <List
      grid={{ 
        gutter: 16,
        xs: 1,
        sm: 1,
        md: 2,
        lg: 3,
        xl: 3,
        xxl: 4,
      }}
      dataSource={dataSource}
      renderItem={renderListItem}
      loading={loading}
      pagination={pagination}
    />
  );
};

export default ListItems; 